package com.ayf.payment.game.api.service.payment;

import com.ayf.payment.game.api.dto.OrderAndMerchantDTO;
import com.ayf.payment.game.api.dto.platform.MerchantPaymentProductDTO;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.entity.Partition;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.service.payment.util.PackageHtmlPayementFormUtil;
import com.ayf.payment.game.api.utils.Md5Utils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author wwl
 * @description:
 * @date 2020/5/13 13:45
 */
@Service
public class WANXPaymentService extends IPaymentService {

    @Override
    public Map<String, Object> paymentUtil(Order order, Partition partition, String orderCreateStr, String traceId, String redirectUrl) {
        Map<String, Object> map=new HashMap<>();
        MerchantPaymentProductDTO merchantPaymentProductDTO = systemInitialization.productDTO(order.getPayTypeId());
        PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(merchantPaymentProductDTO.getcId());
        BigDecimal actualOrderAmt = getActualOrderAmt(order.getAmount(),paymentChannelDTO.getId(),partition.getMerchantId());
        String KeyValue = paymentChannelDTO.getChannelKey();
        String parter = paymentChannelDTO.getAccountNumber();
        String returnUrl=paymentChannelDTO.getReturnUrl();
        String AuthorizationURL = paymentChannelDTO.getPaymentUrl();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} 失败，通道下单地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.substring(0,AuthorizationURL.length()-1);
        }
        if (StringUtils.isEmpty(returnUrl)){
            LogPortal.error("{} 失败，异步通知地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!returnUrl.endsWith("/")){
            returnUrl=returnUrl.concat("/");
        }
        Map<String, String> mapParam = new LinkedHashMap<>();
        mapParam.put("version","2.1");
        mapParam.put("parter",parter);
        mapParam.put("type",getPayCode(merchantPaymentProductDTO.getBusinessCode()));
        mapParam.put("amount",String.valueOf(actualOrderAmt.setScale(2, BigDecimal.ROUND_DOWN)));
        mapParam.put("orderno",order.getMerchantOrderNo());
        mapParam.put("recefiveurl",returnUrl.concat("gameapip/v/wanx/pay/returns"));
        mapParam.put("notifyurl",returnUrl.concat("gameapip/v/wanx/pay/notify"));
        mapParam.put("remark",redirectUrl);
        mapParam.put("orderencodetype","MD5");
        String sign = getOrderPaySign(mapParam,KeyValue);
        mapParam.put("sign",sign);
        mapParam.put("username","");
        String payFormHmtl = PackageHtmlPayementFormUtil.packageHtmlPayementForm(mapParam,AuthorizationURL);
        LogPortal.info("{} 商户ID[{}] 商户订单号[{}] 万象下单请求报文[{}]", traceId, order.getMerchantId(), order.getMerchantOrderNo(),AuthorizationURL,payFormHmtl);
        order.setRandomAmt(BigDecimal.ZERO);
        order.setOrderNo("");
        order.setPayChannleName(paymentChannelDTO.getName());
        order.setPayChannleId(paymentChannelDTO.getId());
        order.setPayTypeId(merchantPaymentProductDTO.getProductId());
        order.setPayTypeName(merchantPaymentProductDTO.getProductName());
        order.setMerchantIncome(BigDecimal.ZERO);
        order.setPlatformIncome(BigDecimal.ZERO);
        order.setFee(BigDecimal.ZERO);
        order.setChannelIncome(BigDecimal.ZERO);
        orderMapper.insertSelective(order);
        map.put("code","002");
        map.put("htmlMsg",payFormHmtl);
        return map;
    }


    private String getOrderPaySign(Map<String, String> signParam,String key) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : signParam.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue() + "&");
        }
        String signOriginStr = sb.toString();
        signOriginStr=signOriginStr.concat("key=").concat(key);
        String sign = Md5Utils.md5LowerCase(signOriginStr);
        if (StringUtils.isEmpty(sign)) {
            return null;
        }
        return sign.toLowerCase();
    }

    @Override
    public void queryPayOrder(OrderAndMerchantDTO dto, String traceId) {

    }

    private String getPayCode(String code){
        if("ALIPAY".equals(code)||"ANTCREDITPAY".equals(code)){
            return "ALIPAY";
        } else if("WECHAT".equals(code)){
            return "WEIXIN";
        } else {
            throw new NullSetException("该通道不支持充值，请更换其他通道充值！");
        }
    }

}
